package com.apkcore.core.ui

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import androidx.annotation.LayoutRes
import androidx.fragment.app.Fragment
import androidx.fragment.app.createViewModelLazy
import androidx.fragment.app.viewModels
import androidx.lifecycle.HasDefaultViewModelProviderFactory
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner
import androidx.lifecycle.viewmodel.CreationExtras
import androidx.viewbinding.ViewBinding
import com.apkcore.core.viewbinding.viewBinding

abstract class BaseFragment<VB : ViewBinding>(
    @LayoutRes resId: Int,
    viewBinder: (View) -> VB
) :
    Fragment(resId) {
    //abstract class BaseFragment<VM : ViewModel>(@LayoutRes resId: Int) : Fragment(resId) {
    private var isFirst: Boolean = true
    private val handler = Handler(Looper.getMainLooper())
    val binding: VB by viewBinding(viewBinder)

//    val mViewModel: VM by lazy { ViewModelProvider(this)[getVmClazz(this)] }
//
//    private fun <VM> getVmClazz(obj: Any): VM {
//        return (obj.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as VM
//    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        isFirst = true
        initView(savedInstanceState)
        initData()
        createObserver()
    }

    abstract fun initView(savedInstanceState: Bundle?)
    abstract fun initData()
    open fun lazyLoadData() {}
    open fun createObserver() {}

    override fun onResume() {
        super.onResume()
        onVisible()
    }

    private fun onVisible() {
        if (lifecycle.currentState == Lifecycle.State.STARTED && isFirst) {
            // 延迟加载 防止 切换动画还没执行完毕时数据就已经加载好了，这时页面会有渲染卡顿
            handler.postDelayed({
                lazyLoadData()

                isFirst = false
            }, lazyLoadTime())
        }
    }

    open fun lazyLoadTime(): Long {
        return 300L
    }

    override fun onDestroy() {
        handler.removeCallbacksAndMessages(null)
        super.onDestroy()
    }

}